package barrage

import (
	"encoding/json"
	"game_server/framework/global"
	"game_server/framework/message"
	"game_server/framework/task"
	"game_server/game"
	"game_server/proto"
	"github.com/duke-git/lancet/v2/convertor"
	"strings"
)

type BarrageSendReq struct {
	Content   string `json:"content"`
	RoomLevel int    `json:"roomLevel"`
}

func BarrageHandler(taskWrapper *task.TaskWrapper) *task.TaskWrapper {
	defer func() {
		err := recover()
		if err != nil {
			global.Logger.Errorf("err:%v", err)
		}
	}()
	defer global.Logger.Info("package:[barrage]:::function:[BarrageHandler]<======")
	global.Logger.Infof("======>package:[barrage]:::function:[BarrageHandler]:::id:%v", taskWrapper.ReceiverId)
	barrageSendReq := &BarrageSendReq{}
	json.Unmarshal([]byte(convertor.ToString(taskWrapper.MessageWrapper.Data)), barrageSendReq)
	roomInfo := game.GameManagerInstance().RoomInfos[barrageSendReq.RoomLevel]
	if roomInfo == nil {
		return nil
	}
	words := strings.Split(roomInfo.RoomConfig.BarrageWords, ",")
	flag := false
	for _, v := range words {
		if strings.Contains(barrageSendReq.Content, v) {
			flag = true
			break
		}
	}
	if flag {
		messageWrapper := &message.MessageWrapper{Code: proto.BarrageSend, Data: nil, ResultCode: message.FAIL, MsgCode: 4}
		task := &task.TaskWrapper{
			ReceiverId:     taskWrapper.ReceiverId,
			MessageWrapper: messageWrapper,
			SenderIds:      []int64{taskWrapper.ReceiverId},
		}
		return task
	} else {
		roomInfo.BarrageBroadcast(barrageSendReq.Content)
		messageWrapper := &message.MessageWrapper{Code: proto.BarrageSend, Data: nil, ResultCode: message.SUCCESS, MsgCode: 0}
		task := &task.TaskWrapper{
			ReceiverId:     taskWrapper.ReceiverId,
			MessageWrapper: messageWrapper,
			SenderIds:      []int64{taskWrapper.ReceiverId},
		}
		return task
	}
}
